<template>
  <div id="app">
    <el-container>
      <el-header>
        <div id="pilot">
          <el-row :gutter="60">
            <el-col :span="14">
              <div style="width: 50%">
                <el-form  @submit.native.prevent>
                  <el-form-item>
                    <el-input
                        placeholder="搜索书籍关键字"
                        prefix-icon="el-icon-search"
                        v-model="searchText"
                        @keydown.enter.native = "search"
                        clearable
                    >
                      <el-button
                          slot="append"
                          type="primary"
                          @click="search">搜索</el-button>

                    </el-input>
                  </el-form-item>

                </el-form>
              </div>
            </el-col>
            <el-col :span="10">
              <div style="float: right">

                <el-button type="primary" @click="addBookVisible = true">添加书籍</el-button>
                <el-button type="success" @click="clearCache()">清理缓存</el-button>
                <el-button type="danger" :disabled="deleteToggle" @click="deleteBooksBySelection">删除</el-button>

              </div>
            </el-col>
          </el-row>
        </div>
      </el-header>
      <el-main>
        <div class="table">
          <el-table
              v-loading="loading"
              :data="tableData"
              border
              style="width: 100%"
              @selection-change="handleSelectionChange"
              :cell-style="{'text-align':'center'}"
          >
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column
                label="封面"
                width="120">
              <template slot-scope="scope" style="margin: 0">
                <img :src="scope.row.bookImg | url" alt="" style="width: 100px;border-radius: 10px;">
              </template>

            </el-table-column>
            <el-table-column
                prop="bookName"
                label="书名"
                width="120">
            </el-table-column>
            <el-table-column
                prop="bookAuthor"
                label="作者"
                width="120">
            </el-table-column>
            <el-table-column
                prop="bookTotal"
                label="字数(万)"
                width="120">
            </el-table-column>
            <el-table-column
                prop="type"
                label="类型"
                width="">
            </el-table-column>
            <el-table-column
                label="免费"
                width="">
              <el-tag slot-scope="scope" effect="dark" :type="scope.row.free ? 'success' : 'danger'">
                {{scope.row.free ? '免费' : '付费'}}
              </el-tag>
            </el-table-column>
            <el-table-column
                label="完本"
                width="">

              <el-tag slot-scope="scope" effect="dark" :type="scope.row.full ? '' : 'warning'" >
                {{scope.row.full ? '完本' : '连载'}}
              </el-tag>
            </el-table-column>
            <el-table-column
                prop="bookPath"
                label="文件路径"
                width="">
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="200">
              <template slot-scope="scope">
                <el-row :gutter="10">
                  <el-col :span="8">
                    <el-button type="primary" icon="el-icon-edit" circle size="small" @click="editBook(scope.row)"/>
                  </el-col>
                  <el-col :span="8">
                    <el-popconfirm
                        confirm-button-text='好的'
                        cancel-button-text='不用了'
                        icon="el-icon-info"
                        icon-color="red"
                        title="数据无价,确定删除吗？"
                        @confirm="deleteBookByRow(scope.row.bookNumber)"
                    >
                    <el-button slot="reference" size="small" type="danger" circle icon="el-icon-delete"/>
                    </el-popconfirm>
                  </el-col>
                  <el-col :span="8"></el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>

        </div>
        </el-main>
      <el-footer>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="current_change"/>
      </el-footer>
    </el-container>
    <el-dialog title="编辑" :visible.sync="dialogVisible" width="700px">
      <BookEditComponent :key="new Date().getTime()" :book="currentBook" v-on:dialogVisible="dialogVisible=false,forceUpdate()"/>
    </el-dialog>
    <el-dialog title="添加书籍" :visible.sync="addBookVisible" width="700px">
      <BookEditComponent :key="new Date().getTime()" :book="newBook" v-on:addBookVisible="addBookVisible=false,forceUpdate()"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  clearCache,
  countBookList,
  delBooksByNumberList,
  getBookList,
  getCountSearchBook,
  searchBook
} from "@/utils/api";
import BookEditComponent from "@/components/manage/book/BookEditComponent";

export default {
  name: "ManageBookComponent",
  components: { BookEditComponent},
  props: {},
  data() {
    return {
      loading: false,
      searchText:'',
      currentPage :1,
      total : 0,
      pageSize : 5,
      tableData: [],
      dialogVisible: false,
      addBookVisible:false,
      currentBook:Object,
      deleteToggle:true,
      selection:Array,
      newBook :{
        bookNumber : '',
        bookName : '',
        bookImg : '',
        bookAuthor : '',
        bookStart : '',
        bookIntroduce : '',
        bookTotal : '',
        type : '',
        free : true,
        full : true,
        bookPath : ''
      }
    }
  }, methods: {
    clearCache(){
      this.loading = true
      clearCache(null).then(res=>{
        if(res.code == 200){
          setTimeout(() => {
            this.loading = false
          }, 1000);
        }
      })
    },
    deleteBookByRow(number){
      this.deleteBooks([number])
    },
    deleteBooksBySelection(){
      let numberList =[]
      for (const selectionElement of this.selection) {
        numberList.push(selectionElement.bookNumber)
      }
      // console.log(numberList)
      this.deleteBooks(numberList)
    },
    async deleteBooks(numberList){
      // console.log("删除!"+numberList)
      delBooksByNumberList(
        numberList
      ).then(res=>{
        if(res.code === 200){
          this.notify(res.message,"","success")
          for (var i = 0; i < this.tableData.length; i++){
            if(numberList.includes(this.tableData[i].bookNumber)) {
              this.tableData.splice(i--, 1);
            }
          }
          if(this.tableData.length==0){
            this.currentPage--
            this.load()
          }
        }else{
          this.notify(res.message,"","error")
        }
      })
    },
    handleSelectionChange(selection){
      this.deleteToggle = selection.length==0
      // console.log(selection)
      this.selection = selection
    },
    editBook(row){
      this.currentBook = row
      this.dialogVisible = true
    },
    search(){
      // let keyword = this.searchText;
      this.getCountSearchBook()
      this.searchBook()
    },
    async searchBook(){
      searchBook({
        keyword : this.searchText,
        currentPage : this.currentPage,
        pageSize : this.pageSize
      }).then(res=>{
        if(res.code === 200){
          // this.notify(res.message,"","success")
          // console.log(res)
          this.tableData = res.objects
        }else{
          this.notify(res.message,"","error")
        }
      })
    },
    async getCountSearchBook(){
      getCountSearchBook({
        keyword : this.searchText
      }).then(res=>{
        if(res.code === 200){
          this.total = res.objects
        }else{
          this.notify(res.message,"","error")
        }
      })
    },
    current_change(newPage){
      this.currentPage = newPage
      this.load()
    },
    forceUpdate(){
      this.loading=true
      setTimeout(res=>{
        console.log("update ")
        this.$forceUpdate()
        this.load()
        this.loading=false
      },1000)
    },
    async load(){
      this.tableData = []
      this.loading=true
      getBookList({
        currentPage : this.currentPage,
        pageSize : this.pageSize
      }).then(res=>{
        this.loading=false
        if(res.code === 200){
          // this.notify(res.message,"","success")
          // console.log(res)
          this.tableData = res.objects
        }else{
          this.notify(res.message,"","error")
        }
      })


      // this.current_change(this.currentPage)
    },
    getBookTotal(){
      countBookList().then(res=>{
        if(res.code === 200){
          this.total = res.objects
        }else{
          this.notify(res.message,"","error")
        }
      })
    },
    notify(msg,title,type) {
      this.$notify({
        title: title,
        message: msg,
        type: type
      });
    },
    log(msg,type){
      this.$message({
        message: msg,
        type: type
      });
    }
  }, watch: {
    searchText(newName, oldName){
      if(newName === ''){

        // this.pageSize = 5
        this.getBookTotal()
        this.current_change(1)
      }
    }
  }, computed: {},mounted() {
    this.getBookTotal()
    this.current_change(1)
  },filters:{
    url(value){
      return '/api'+value;
    }
  }
}
</script>

<style scoped>
.table{
}
</style>